from ..exception.TestException import TestException
from ..common.ui.PageElement import PageElement
from ..exception.errorcode import ErrorCode


class ICheck(PageElement):
    _fish_data_ui_role = 'icheck'

    def setValue(self, value):
        self.choose(value)

    def choose(self, value):
        self.wait_element_presence()
        match, _ = self.check_fish_data_role_id(raise_exception=False)
        self.check_fish_data_role_id(raise_exception=False)
        if match is True:
            get_value_script = 'return $(arguments[0]).parent().parent().text().trim()'
        else:
            # 兼容非Fish ICheck组件情况，特殊处理，取一层
            # TODO 需要细化虚招radio
            get_value_script = 'return $(arguments[0]).parent().text().trim()'
        elements = self._get_web_elements()
        for element in elements:
            select_value = self._execute_script(get_value_script, element)
            if value == select_value:
                self._execute_script('$(arguments[0])[0].click()', element)
                self._execute_script('$(arguments[0]).change()', element)
                return
        raise TestException.by_error_code(ErrorCode.ICHECK_VALUE_NOT_FIND, value=value)

    def click(self):
        self.wait_element_presence()
        self._execute_script('$(arguments[0]).click()', self._get_web_elements())

    def get_identification(self):
        identification = {'data-ui-role': ['icheck']}
        return identification

